<?php
namespace app\common\order\model;

use app\common\config\logic\CommonPickerLogic;
use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigCompany;
use app\common\config\model\ConfigHall;
use app\common\config\model\ConfigStore;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\product\logic\StoreCategoryLogic;
use app\common\system\logic\UserLogic;
use think\db\exception\DataNotFoundException;
use think\Model;
use think\model\concern\SoftDelete;

class Order extends Model
{
    use SoftDelete;
    protected $defaultSoftDelete = 0;
    

    protected $type = [
        'files' => 'json',
        'images' => 'json',
        'contract' => 'json',
        'sign_date' => 'timestamp',
        'event_date' => 'timestamp',
        'check_time' => 'timestamp',
    ];

    public function member()
    {
        return $this->hasOne(Customer::class, "id", "member_id");
    }

    public function product()
    {
        return $this->hasOne(OrderProduct::class, "order_id", "id");
    }

    public function getSourceAttr($value, $data) {
        if(empty($data['source_id'])) return [
            'id' => '',
            'title' => ''
        ];

        $logic = new DictionaryLogic();
        return $logic->getFullPath($data['source_id']);
    }

    public function getCustomerAttr($value, $data) 
    {
        $customerModel = new Customer();
        $fields = "id,fullname,create_id,source_id";
        try {
            $customer = $customerModel->where('id', $data['member_id'])->field($fields)->find();
            $customer->append(['creator', 'source']);
        } catch (DataNotFoundException $e) {
            $customer = [
                'id' => '',
                'fullname' => '',
                'creator' => [
                    'id' => '',
                    'realname' => '',
                ],
                'source' => [
                    'id' => '',
                    'title' => ''
                ]
            ];
        }

        return $customer;
    }

    public function getAllocateAttr($value, $data) {
        if ($data['allocate_id'] > 0) {
            $allocateModel = new CustomerAllocate();
            $allocate = $allocateModel::withTrashed()->where('id', $data['allocate_id'])->field('id,user_id')->find();
            $allocate->append(['user']);
        } else {
            $allocate = [
                'id' => '',
                'user_id' => '',
                'user' => [
                    'id' => '',
                    'realname' => ''
                ]
            ];
        }

        return $allocate;
    }

    public function getCategoryAttr($value, $data) {
        $categoryLogic = new StoreCategoryLogic();
        $category = $categoryLogic->getStoreCategory($data['category_id'], ['id', 'title', 'order_model']);

        if (empty($category)) {
            $category = [
                'id' => '',
                'title' => '',
                'order_model' => ''
            ];
        }

        return $category;
    }

    public function getCompanyAttr($value, $data) {
        $dictionaryLogic = new DictionaryLogic();
        $company = $dictionaryLogic->getItem($data['company_id'], ConfigCompany::class, ['id', 'title', 'short_name']);

        if (empty($company)) {
            $company = [
                'id' => '',
                'title' => '',
                'short_name' => ''
            ];
        }

        return $company;
    }

    public function getWeddingAttr($value, $data) {
        $default = [
            'id' => '',
            'product_id' => '',
            'company_id' => '',
            'total' => '',
            'product' => [
                'id' => '',
                'title' => '',
                'titlepic' => '',
                'price' => ''
            ],
            'company' => [
                'id' => '',
                'title' => '',
                'short_name' => ''
            ]
        ];
        // 2 = 婚庆; 4 = 一站式;
        if ($data['category_id'] == 2 || $data['category_id'] == 4) {
            $orderProductModel = new OrderProduct();
            $where = [];
            $where[] = ['order_id', '=', $data['id']];
            $where[] = ['category_id', '=', 2];
            $wedding = $orderProductModel->where($where)->field('id,product_id,company_id,total')->find();
            if ($wedding) {
                $wedding->append(['product', 'company']);
                return $wedding;
            } else {
                return $default;
            }
        } else {
            return $default;
        }
    }

    public function getWeddingCompanyAttr($value, $data) {
        // 2 = 婚庆; 4 = 一站式
        if ($data['category_id'] == 2 || $data['category_id'] == 4) {
            $orderProductModel = new OrderProduct();
            $where = [];
            $where[] = ['order_id', '=', $data['id']];
            $where[] = ['category_id', '=', 2];
            $wedding = $orderProductModel->where($where)->field('id,company_id')->find();
            if ($wedding) {
                $wedding->append(['company']);
                return $wedding['company'];
            } else {
                return [
                    'id' => '',
                    'title' => '',
                    'short_name' => ''
                ];
            }
        } else {
            return [
                'id' => '',
                'title' => '',
                'short_name' => ''
            ];
        }
    }

    public function getCooperationAttr($value, $data) {
        $commonLogic = new CommonPickerLogic();
        $cooperation = $commonLogic->getPickerItem('cooperation', $data['cooperation_id']);

        if (empty($cooperation)) {
            $cooperation = [
                'id' => '',
                'title' => ''
            ];
        }
        return $cooperation;
    }

    public function getStoreAttr($value, $data) {
        $dictionaryLogic = new DictionaryLogic();
        $store = $dictionaryLogic->getItem($data['store_id'], ConfigStore::class, ['id', 'title']);

        if (empty($store)) {
            $store = [
                'id' => '',
                'title' => ''
            ];
        }

        return $store;
    }

    public function getHallAttr($value, $data) {
        $dictionaryLogic = new DictionaryLogic();
        $hall = $dictionaryLogic->getItem($data['hall_id'], ConfigHall::class, ['id', 'title']);

        if (empty($hall)) {
            $hall = [
                'id' => '',
                'title' => ''
            ];
        }
        return $hall;
    }

    public function getBanquetTypeAttr($value, $data) {
        $commonLogic = new CommonPickerLogic();
        return $commonLogic->getPickerItem('banquetType', $data['banquet_type_id']);
    }

    public function getSignDateAttr($value) {
        return date('Y-m-d', $value);
    }

    public function getEventDateAttr($value) {
        return date('Y-m-d', $value);
    }

    public function getUserAttr($value, $data) {
        $userLogic = new UserLogic();
        return $userLogic->getUser($data['user_id'], ['id', 'realname', 'work_wechat']);
    }

    public function getOrderTypeTextAttr($value, $data) {
        $index = $data['order_type'];
        $map = [
            1 => '订单',
            2 => '返佣单',
            3 => '定金订单',
            4 => '意向金订单'
        ];

        return $map[$index];
    }

    public function getCheckTagAttr($value, $data) {
        $index = $data['check_status'];
        $map = [
            -1 => '暂存',
            0 => '待审核',
            1 => '审核中',
            2 => '审核通过',
            3 => '审核驳回'
        ];

        return $map[$index];
    }

    public function getCollectsAttr($value, $data) {
        $model = new OrderCollect();
        $rows = $model->where('order_id', $data['id'])->select();
        foreach ($rows as $row) {
            $row->append(['title', 'check_tag']);
        }

        // 判断是否为空
        if ($rows->isEmpty()) {
            $rows = [];
            $rows[] = [ 'id' => 0, 'type' => 1, 'title' => '定金', 'check_tag' => '', 'price' => '',  'collect_date' => '' ];
            $rows[] = [ 'id' => 0, 'type' => 2, 'title' => '中款', 'check_tag' => '', 'price' => '',  'collect_date' => '' ];
            $rows[] = [ 'id' => 0, 'type' => 3, 'title' => '尾款', 'check_tag' => '', 'price' => '',  'collect_date' => '' ];
            return $rows;
        } else {
            return $rows->toArray();
        }
    }

    public function getIncomeAttr($value, $data) {
        $model = new OrderIncome();
        $rows = $model->where('order_id', $data['id'])->select();

        $group = [
            'earnest' => [
                'total' => 0,
                'date' => '',
            ],
            'middle' => [
                'total' => 0,
                'date' => '',
            ],
            'tail' => [
                'total' => 0,
                'date' => '',
            ],
            'other' => [
                'total' => 0,
                'date' => '',
            ]
        ];
        foreach($rows as $row) {
            switch ($row['income_type_id']) {
                case 1:
                    $group['earnest']['total'] +=  $row['total'];
                    $group['earnest']['date'] = $row['income_date'];
                    break;
                case 2:
                    $group['middle']['total'] += $row['middle'];
                    $group['middle']['date'] = $row['income_date'];
                    break;
                case 3:
                    $group['tail']['total'] += $row['tail'];
                    $group['tail']['date'] = $row['income_date'];
                    break;
                default:
                    $group['other']['total'] += $row['other'];
                    $group['other']['date'] = $row['income_date'];
            }
        }

        return $group;
    }

    // 获取返佣单信息
    public function getRebateAttr($value, $data) {
        $rebate = [
            'id' => 0,
            'price' => 0,
            'amount' => 0,
            'total' => 0,
            'real_total' => 0,
            'percent' => 0,
            'settle_time' => 0
        ];

        if ($data['order_type'] == 2) {
            $model = new OrderSettle();
            $fields = ['id', 'price', 'amount', 'total', 'real_total', 'percent', 'settle_time'];
            $row = $model->where('order_id', $data['id'])->field($fields)->find();
            if (!empty($row)) {
                $rebate = $row->toArray();
            }
        }

        return $rebate;
    }

    public function setImagesAttr($value) {
        return empty($value) ? '[]' : json_encode($value);
    }

    public function getImagesAttr($value) {
        return empty($value) ? [] : json_decode($value, true);
    }

    public function setContractAttr($value) {
        return empty($value) ? '[]' : json_encode($value);
    }

    public function getContractAttr($value) {
        return empty($value) ? [] : json_decode($value, true);
    }
}